package com.ququ.syb.balance.service;

import com.alibaba.fastjson.JSON;
import com.ququ.common.result.Result;
import com.ququ.syb.balance.fegin.AccountBalanceFlowFegin;
import com.ququ.syb.balance.rabbitmq.RabbitMQSender;
import com.ququ.syb.common.constant.RabbitMqQueueNameConstant;
import com.ququ.syb.common.pojo.AccountBalanceFlow;
import com.ququ.syb.common.pojo.AccountChannelBalance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AccountChannelBalanceBusinessService {
    @Autowired
    private AccountChannelbalanceService accountChannelbalanceService;
    @Autowired
    private RabbitMQSender rabbitMQSender;
    @Autowired
    private AccountBalanceFlowFegin accountBalanceFlowFegin;

    public AccountChannelBalance addBalance(String accountid,String channelid,Long amount,Integer ordertype,String tradenum,Integer flowtype,String appcode,String remark){
        Result<List<AccountBalanceFlow>> flowResult = accountBalanceFlowFegin.listAccountBalanceFlow(accountid, tradenum, amount, flowtype,remark);
        if (flowResult.getStatus() == -1) {
            AccountChannelBalance accountChannelBalanceBefore = accountChannelbalanceService.getAccountChannelBalance(accountid, channelid);
            AccountChannelBalance accountChannelBalanceAfter = accountChannelbalanceService.addBalance(accountid, channelid, amount);
            Map<String, Object> flowMap = new HashMap<>();
            flowMap.put("accountid", accountid);
            flowMap.put("channelid", channelid);
            flowMap.put("currentbalance", accountChannelBalanceBefore==null?0L:accountChannelBalanceBefore.getBalance());
            flowMap.put("amount", amount);
            flowMap.put("afterbalance", accountChannelBalanceAfter.getBalance());
            flowMap.put("tradenum", tradenum);
            flowMap.put("ordertype", ordertype);
            flowMap.put("flowtype", flowtype);
            flowMap.put("appcode", appcode);
            flowMap.put("remark", remark);
            flowMap.put("time", new Date());
            rabbitMQSender.send(RabbitMqQueueNameConstant.FLOW_ACCOUNT_BALANCE, JSON.toJSONString(flowMap));
            return accountChannelBalanceAfter;
        }else
            return null;
    }
}
